package com.chat.demo.userservice;

import com.chat.demo.auth.JwtUtils;
import com.chat.demo.userservice.DTO.FriendShip.FriendApplyDTO;
import com.chat.demo.userservice.DTO.FriendShip.FriendInfo;
import com.chat.demo.userservice.DTO.FriendShip.FriendRequestDTO;
import com.chat.demo.userservice.DTO.FriendShip.FriendsListDTO;
import com.chat.demo.userservice.Entity.DAO.FriendRequestDao;
import com.chat.demo.userservice.Entity.DAO.FriendshipDao;
import com.chat.demo.userservice.Entity.Entity.FriendRequest;
import com.chat.demo.userservice.Entity.Entity.UserDao;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class Friend_Service {
    @Autowired
    private FriendshipDao friendshipDao;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserDao userDao;
    @Autowired
    private FriendRequestDao friendRequestDao;

    public Long getIdFromRequest(HttpServletRequest request){
        String token = jwtUtils.getTokenFromHeader(request);
        String username = jwtUtils.getUsernameFromToken(token);
        System.out.println("username = " + username);
        System.out.println("userId = " + userDao.findUserByUsername(username).getUserId());
        return Long.valueOf(userDao.findUserByUsername(username).getUserId());
    }
    public void sendFriendRequest(Long senderId,Long receiverId) {
        friendshipDao.createFriendRequest(senderId,receiverId);
    }

    @Transactional
    public void acceptFriendRequest(Long requestId) {
        // Step 1: 查询请求中的 sender_id 和 recipient_id
        FriendRequestDTO ids = friendshipDao.getSenderIdAndReceiverId(requestId);
        System.out.println("request = " + ids);
        if (ids.getRecipientId() == null || ids.getSenderId() == null) {
            throw new RuntimeException("请求不存在");
        }
        Long senderId = ids.getSenderId();
        Long receiverId = ids.getRecipientId();
        // Step 2: 删除请求记录
        friendshipDao.deleteFriendRequestById(requestId);
        // Step 3: 插入好友关系（自动排序）
        friendshipDao.insertFriendship(senderId, receiverId);
    }

    @Transactional
    public List<FriendsListDTO> getFriends(HttpServletRequest request) {
        Long userId = getIdFromRequest(request);
        List<Long> friendIds = friendshipDao.findActiveFriendIdsByUserId(userId);
        List<FriendsListDTO> list = new ArrayList<>();
        for (Long friendId : friendIds) {
            FriendsListDTO item = new FriendsListDTO(friendId, userDao.findUserById(friendId).getUsername());
            list.add(item);
        }
        return list;
    }

    @Transactional
    public void rejectFriendRequest(Long requestId) {
        friendshipDao.deleteFriendRequestById(requestId);
    }

    @Transactional
    public void removeFriendship(Long myId, Long brokeId) {
        friendshipDao.deleteFriendshipById(myId,brokeId);
    }

    @Transactional
    public boolean checkIfAreFriends(Long a, Long b) {
        return friendshipDao.isFriends(a, b);
    }

    @Transactional
    public List<FriendInfo> getActiveFriends(HttpServletRequest request) {
        Long userId = getIdFromRequest(request);
        return friendshipDao.findActiveFriendsByUserId(userId);
    }

    @Transactional
    public List<FriendApplyDTO> getPendingRequestsByUserId(Integer userId) {
        List<FriendRequest> rs = friendRequestDao.getPendingRequestsByUserId(userId);
        List<FriendApplyDTO> rsWithName = new ArrayList<>();
        for (FriendRequest request : rs) {
            String senderName = userDao.findUserById(Long.valueOf(request.getSenderId())).getUsername();
            rsWithName.add(new FriendApplyDTO(request, senderName));
        }
        return rsWithName;
    }

}
